package com.wl.wuliu.exception;

import com.wl.wuliu.config.constant.HttpStatus;
import com.wl.wuliu.result.AjaxResult;
import com.wl.wuliu.utils.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.sql.SQLException;

/**
 * 通用异常处理
 * @Author: gutaozhen
 * @Date: 2022/6/13
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler({Exception.class})
    public @ResponseBody
    AjaxResult handleException(Exception e) {
        AjaxResult result = new AjaxResult();
        result.put("code", HttpStatus.ERROR);

        log.error("异常信息：", e);

        if (e instanceof TransactionSystemException) {
            Throwable t = e.getCause();
            while ((t != null) && !(t instanceof ConstraintViolationException)) {
                t = t.getCause();
            }
            if (t instanceof ConstraintViolationException) {
                return new AjaxResult(HttpStatus.ERROR, ExceptionUtils.getMessage(t));
            }
        } else if (e instanceof SQLException || e instanceof DataIntegrityViolationException) {
            result.put("msg", "输入数据格式错误！");
        } else if (e.getMessage().indexOf("Subject does not have permission") >= 0) {
            result.put("msg", "对不起，您暂时没有权限访问该资源");
        } else {
//            result.put("msg", "系统异常！" + e.getMessage());
            result.put("msg", "系统异常！");
        }
        return result;
    }

    @ExceptionHandler(CustomException.class)
    public AjaxResult businessException(CustomException e)
    {
        if (StringUtils.isNull(e.getCode()))
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error(e.getCode(), e.getMessage());
    }
}
